package net.toocruel.iqismart.web.init;

import net.toocruel.iqismart.dao.core.CategoryRepository;
import net.toocruel.iqismart.entity.dto.TimeOffset;
import net.toocruel.iqismart.entity.setting.Setting;
import net.toocruel.iqismart.service.SettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;

import javax.persistence.EntityManagerFactory;
import java.util.HashMap;
import java.util.Map;

/**
 * 每次启动时 取出配置 放到模板静态变量里
 *
 * @author toocruel
 *
 */
@Component
public class SettingDataInitializer extends AbstractDataInitializer implements DataInitializer {

    @Autowired
    private EntityManagerFactory entityManagerFactory;

    @Autowired
    private SettingService settingService;

    @Autowired
    private CategoryRepository categoryRepository;

    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;

    @Override
    protected void doInit() throws Exception {
        try {
            if (thymeleafViewResolver != null) {
                Map<String, Object> vars = new HashMap<>();
                Setting setting = settingService.getSetting();
                Setting.SETTING = setting;
                vars.put("GlobalSetting", setting);
                vars.put("GlobalTimeOffset", TimeOffset.ALL);
                vars.put("Categotys", categoryRepository.findAll());
                vars.put("", categoryRepository.findAll());
                thymeleafViewResolver.setStaticVariables(vars);
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(SettingDataInitializer.class.getSimpleName()+"执行失败");
        }

    }

    @Override
    protected boolean isNeedInit() {
        return true;
    }

    @Override
    public Integer getIndex() {
        return 1;
    }
}
